<template>
	<div>
		<ProTable ref="proTable" title="抽奖管理" :columns="columns" :request-api="getTableList" :init-param="initParam">
			<template #searchHeader>
				<div class="mb16">
					<el-button type="primary" v-auth="'draw:activity:create:invoke'" @click="toAdd"> 新增活动 </el-button>
				</div>
			</template>
			<!-- 表单 头部 数据 -->
			<template #tableHeader>
				<el-tabs v-model="activeTag" class="demo-tabs" @tab-click="handleTab">
					<el-tab-pane v-for="item in tags" :key="item.name" :label="`${item.label}(${item.data})`" :name="item.name"></el-tab-pane>
				</el-tabs>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button type="primary" link :loading="previewLoading" @click="onPreview(row)" v-auth="'draw:activity:preview:invoke'"> 预览 </el-button>
				<el-divider direction="vertical" v-auth="'draw:activity:preview:invoke'" />
				<el-button type="primary" link @click="onLink(row)" v-auth="'draw:activity:link:invoke'"> 链接 </el-button>
				<el-divider direction="vertical" v-auth="'draw:activity:link:invoke'" />
				<el-button type="primary" link v-auth="'draw:activity:data:invoke'" @click="$router.push({ path: `/lottery/list/data/${row.id}` })">
					数据
				</el-button>
				<el-divider direction="vertical" v-auth="'draw:activity:data:invoke'" />
				<el-button
					type="primary"
					link
					v-auth-all="['draw:activity:edit:invoke', 'draw:activity:details:invoke']"
					@click="$router.push({ path: `/lottery/list/edit/${row.id}` })"
				>
					编辑
				</el-button>
				<el-divider direction="vertical" v-auth-all="['draw:activity:edit:invoke', 'draw:activity:details:invoke']" />
				<el-button type="primary" link v-auth="'draw:activity:delete:invoke'" @click="onDelete(row.id)"> 删除 </el-button>
			</template>
		</ProTable>
		<Audit :visible="auditVisible" :row="auditRow" @handleClose="closeAudit"></Audit>
		<Link :visible="linkVisible" :row="linkRow" @handleClose="closeLink"> </Link>
	</div>
</template>

<script setup lang="tsx" name="lotteryList">
import { onMounted, ref, reactive, computed, nextTick } from 'vue';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchLotteryList, fetchLotteryStatic, fetchDelLottery, fetchQrCode } from '/@/api/lottery';
import Audit from './dialog/audit.vue';
import Link from './dialog/link.vue';

const previewLoading = ref(false);

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

const router = useRouter();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	searchType: 'ID',
	paramTimeType: 'createTime',
});

const activeTag = ref<any>('PROCESSING');
const tags = ref<any>([
	{
		label: '进行中',
		name: 'PROCESSING',
		data: 0,
	},
	{
		label: '待上线',
		name: 'PENDING',
		data: 0,
	},
	{
		label: '已下线',
		name: 'OFFLINE',
		data: 0,
	},
]);

const handleTab = () => {
	nextTick(() => {
		proTable.value?.getTableList();
	});
};

const initStatics = async (params: any) => {
	const { code, data } = await fetchLotteryStatic(params);
	if (code == 200) {
		tags.value = [
			{
				label: '进行中',
				name: 'PROCESSING',
				data: data.processingCount,
			},
			{
				label: '待上线',
				name: 'PENDING',
				data: data.pendingCount,
			},
			{
				label: '已下线',
				name: 'OFFLINE',
				data: data.offlineCount,
			},
		];
	}
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = {
		...params,
		status: activeTag.value,
	};

	if (data.paramTime) {
		data.startTime = dayjs(data.paramTime[0]).format('YYYY-MM-DD HH:mm:ss');
		data.endTime = dayjs(data.paramTime[1]).format('YYYY-MM-DD HH:mm:ss');
	}

	delete data.paramTimeType;
	delete data.paramTime;
	initStatics(data);
	return fetchLotteryList(data);
};

const searchArr = [
	{
		label: '活动ID',
		value: 'ID',
	},
	{
		label: '活动名称',
		value: 'NAME',
	},
];

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'keywords',
		label: '活动搜索',
		isShow: false,
		search: {
			span: 2,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.searchType}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.searchType = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'paramTime',
		label: '活动时间',
		isShow: false,
		search: {
			span: 2,
			render: (scope: any) => {
				return (
					<div class="flex-center">
						<el-select
							v-model={scope.searchParam.paramTimeType}
							placeholder="Select"
							style="width: 100px"
							class="mini-gray-select flex-shrink"
							onChange={(value) => (scope.searchParam.paramTimeType = value)}
						>
							{[
								{
									label: '活动时间',
									value: 'createTime',
								},
							].map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
						<el-date-picker
							v-model={scope.searchParam.paramTime}
							type="datetimerange"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							format="YYYY-MM-DD HH:mm:ss"
							date-format="YYYY-MM-DD"
							time-format="HH:mm:ss"
						/>
					</div>
				);
			},
		},
	},
	{
		prop: 'id',
		label: '活动ID',
		minWidth: 100,
	},

	{
		prop: 'name',
		label: '活动名称',
		minWidth: 120,
	},
	{
		prop: 'time',
		label: '活动时间',
		minWidth: 300,
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 280, align: 'left' },
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.searchType;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const auditVisible = ref(false);
const auditRow = ref();

const linkVisible = ref(false);
const linkRow = ref();

const toAdd = () => {
	router.push('/lottery/list/add');
};

const onPreview = async (row: any) => {
	previewLoading.value = true;
	const { data } = await fetchQrCode({ id: row.id });
	previewLoading.value = false;
	ElMessageBox.alert(
		`<div class='flex-center'  style='text-align: center;'>
			<div>
				<image style='width:250px;height:250px' src="data:image/png;base64,${data.alipay}"></image>
				<div class='text-regular'>请使用支付宝扫码预览</div>
			</div>
			<div class='ml30'>
				<image style='width:250px;height:250px'  src="data:image/png;base64,${data.wechat}"></image>
				<div class='text-regular'>请使用微信扫码预览</div>
			</div>
		</div>`,
		'预览',
		{
			customStyle: { minWidth: '560px' },
			dangerouslyUseHTMLString: true,
			showConfirmButton: false,
		}
	);
};

const onLink = (row: any) => {
	linkVisible.value = true;
	linkRow.value = row;
};

const closeLink = () => {
	linkVisible.value = false;
	linkRow.value = null;
};

const onDelete = (id: any) => {
	ElMessageBox.confirm('确认删除该活动？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchDelLottery({ id });
		if (res.code == 200) {
			ElMessage.success('删除成功');
			proTable.value?.getTableList();
		}
	});
};

const onAudit = (row: any) => {
	auditVisible.value = true;
	auditRow.value = row;
};

const closeAudit = (success: boolean) => {
	auditVisible.value = false;
	if (success) {
		proTable.value?.getTableList();
	}
};
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
